package com.gsk.test123.config;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

/**
 * AOP根据注解给上下文赋值
 * @ClassName DataSourceAspect
 * @Description TODO
 * @author lide
 * @date 2018年2月27日 下午4:12:01
 */
@Aspect
@Order(1)	//设置AOP执行顺序(需要在事务之前，否则事务只发生在默认库中)
@Component
public class DataSourceAspect {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	//切点
//	@Pointcut("execution(* com.gsk.spiderdbclean.*.dao.service..*.*(..)))")
//    @Pointcut("execution(* com.gsk.test123.service..*(..)))")
    @Pointcut("execution(* com.gsk.test123.service.*.*(..))")
	public void aspect() { }
	
	@Before("aspect()")
	private void before(JoinPoint point) {
		Object target = point.getTarget();
        String method = point.getSignature().getName();
        Class<?> classz = target.getClass();
        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())
                .getMethod().getParameterTypes();
        try {
            Method m = classz.getMethod(method, parameterTypes);
            if (m != null && m.isAnnotationPresent(MyDataSource.class)) {
            	MyDataSource data = m.getAnnotation(MyDataSource.class);
                JdbcContextHolder.putDataSource(data.value().getName());
                logger.info("===============上下文赋值完成:{}",data.value().getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

//        String className = point.getTarget().getClass().getName();
//        String method = point.getSignature().getName();
//        String args = StringUtils.join(point.getArgs(), ",");
//        logger.info("className:{}, method:{}, args:{} ", className, method, args);
//        try {
//            for (DataSourceType type : DataSourceType.values()) {
//                List<String> values = DynamicDataSource.METHOD_TYPE_MAP.get(type);
//                for (String key : values) {
//                    if (method.startsWith(key)) {
//                        logger.info(">>{} 方法使用的数据源为:{}<<", method, key);
//                        JdbcContextHolder.putDataSource(data.value().getName()); ;
//                        DatabaseType types = DatabaseContextHolder.getDatabaseType();
//                        logger.info(">>{}方法使用的数据源为:{}<<", method, types);
//                    }
//                }
//            }
//        } catch (Exception e) {
//            logger.error(e.getMessage(), e);
//        }
        
	}
}
